package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.AuthorService;
import com.heima.common.constants.article.ArticleConstants;
import com.heima.common.exception.CustException;
import com.heima.model.article.dto.ArticleDto;
import com.heima.model.article.dto.ArticleHomeDto;
import com.heima.model.article.dto.ArticleInfoDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper,ApArticle> implements ApArticleService {
    @Resource
    ApArticleMapper apArticleMapper;

    @Value("${file.oss.web-site}")
    private String webSite;
    @Autowired
    AuthorService authorService;
    @Autowired
    ApArticleConfigMapper apArticleConfigMapper;
    @Autowired
    ApArticleContentMapper apArticleContentMapper;
    @Override
    @Transactional
    public ResponseResult saveArtilce(ArticleDto articleDto) {
        //验证参数
        if(articleDto==null){
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //封装article对象
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(articleDto,apArticle);
        //根据作者名称查询作者id
        ApAuthor apAuthor = authorService.getOne(Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getName, articleDto.getAuthorName()));
        if(apAuthor==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章作者不存在");
        }
        apArticle.setAuthorId(Long.valueOf(apAuthor.getId()));
        //判断文章是否存在
        if(apArticle.getId()==null){
            // 普通文章
            apArticle.setComment(0);
            apArticle.setViews(0);
            apArticle.setCollection(0);
            apArticle.setLikes(0);
            save(apArticle);
        }else {
            ApArticle one = getById(apArticle.getId());
            if(one==null){
                log.error("对应文章id的文章不存在，文章id为==>{}",apArticle.getId());
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章数据不存在");
            }
            //删除中间表相关信息
            apArticleConfigMapper.delete(Wrappers.<ApArticleConfig>lambdaQuery().eq(ApArticleConfig::getArticleId,apArticle.getId()));
            apArticleContentMapper.delete(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId,apArticle.getId()));
            updateById(apArticle);
        }
        //插入中间表文章配置表
        //保存article_config 数据
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setIsForward(true);
        apArticleConfig.setIsComment(true);
        apArticleConfig.setIsDown(false);
        apArticleConfig.setIsDelete(false);
        apArticleConfig.setArticleId(apArticle.getId());
        apArticleConfigMapper.insert(apArticleConfig);
        //添加文章内容
        //保存文章article_content 数据
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setContent(articleDto.getContent());
        apArticleContent.setArticleId(apArticle.getId());
        apArticleContentMapper.insert(apArticleContent);
        //返回文章ID
        return ResponseResult.okResult(apArticle.getId());
    }

    /**
     *
     * 根据参数加载文章列表
     * 1 为加载更多
     * 2 为加载最新
     */
    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDto dto) {
        //1 参数检查
        if (dto == null) {
            dto = new ArticleHomeDto();
        }

        //页大小
        Integer size = dto.getSize();
        if (size == null || size <= 0) {
            size = 10;
        }
        if (StringUtils.isBlank(dto.getTag())){
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        //时间
        if (dto.getMaxBehotTime()==null){
            dto.setMaxBehotTime(new Date());
        }
        if (dto.getMinBehotTime()==null){
            dto.setMinBehotTime(new Date());
        }

        //判断类型
        if (!loadtype.equals(ArticleConstants.LOADTYPE_LOAD_MORE)&&!loadtype.equals(ArticleConstants.LOADTYPE_LOAD_NEW)){
            loadtype=ArticleConstants.LOADTYPE_LOAD_MORE;
        }

         //2 执行查询
        List<ApArticle>articleList= apArticleMapper.loadArticleList(dto,loadtype);
        ResponseResult result = ResponseResult.okResult(articleList);
        result.setHost(webSite);
        return result;


    }

    /**
     * 查询文章详情
     * @param dto  文章id
     * @return
     */

    @Override
    public ResponseResult loadArtilceInfo(ArticleInfoDto dto) {
        //1 参数检查
        if (dto == null || dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Long id = dto.getArticleId();
        //2 查询文章配置信息 config
        ApArticleConfig apArticleConfig = apArticleConfigMapper.selectOne(Wrappers.<ApArticleConfig>lambdaQuery().eq(ApArticleConfig::getArticleId, id));

        if (apArticleConfig == null
                || apArticleConfig.getIsDown()
                || apArticleConfig.getIsDelete()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章已下架");
        }
        //查询文章内容
        ApArticleContent apArticleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, id));
        if (apArticleContent == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        //4 返回封装结果
        Map<String,Object> resultMap =new HashMap<>();
        resultMap.put("config",apArticleConfig);
        resultMap.put("content",apArticleContent);
        return ResponseResult.okResult(resultMap);
    }
}
